<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <title>CSV 文件预览</title>
    <style>
      body {
        font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
        margin: 0;
        padding: 0;
        background: #f7f9fb;
        height: 100vh;
        width: 100vw;
      }
      .table-container {
        position: absolute;
        top: 0; left: 0; right: 0; bottom: 0;
        height: 100vh;
        width: 100vw;
        overflow: auto;
        background: #fff;
        border-radius: 0;
        box-shadow: none;
        padding: 0;
        box-sizing: border-box;
      }
      table {
        border-collapse: separate;
        border-spacing: 0;
        width: 100%;
        background: #fff;
        border-radius: 8px;
      }
      td,
      th {
        border: 1px solid #e3e6eb;
        padding: 8px 10px;
        word-break: break-all;
        max-width: 400px;
        text-align: left;
        background: #fff;
        font-size: 15px;
      }
      thead th { 
        background: #f2f5fa;
        position: sticky;
        top: 0;
        z-index: 2;
        font-weight: bold;
        font-size: 16px;
      }
      .even {
        background: linear-gradient(90deg, #f6fafd 0%, #eaf3fb 100%);
      }
      input[type="text"] {
        border: 1px solid #e3e6eb;
        border-radius: 4px;
        padding: 2px 6px;
        font-size: 14px;
        margin-top: 4px;
        width: 90%;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <!-- 使用说明 -->
    <!-- http://192.168.1.101:8080/chfs/shared/showcsv.html?v=1&url=http://192.168.1.101:8080/chfs/shared/2.csv -->
    <!-- http://192.168.1.101:8080/chfs/shared/showcsv.html?v=1&url=http://192.168.1.101:8080/chfs/shared/1.csv?v=1 -->
    <div class="table-container">
      <div id="csv-table"></div>
    </div>
    <script>
  // 设置title为文件名（不含扩展名）
  document.title = location.pathname.split('/').pop().replace(/\.[^.]+$/, '');

  // 解析CSV，兼容引号、逗号
  function parseCSV(text) {
    const rows = [];
    let row = [], cell = "", inQuotes = false;
    for (let i = 0; i < text.length; i++) {
      const char = text[i], nextChar = text[i + 1];
      if (char === '"') {
        if (inQuotes && nextChar === '"') { cell += '"'; i++; }
        else { inQuotes = !inQuotes; }
      } else if (char === "," && !inQuotes) {
        row.push(cell); cell = "";
      } else if ((char === "\n" || char === "\r") && !inQuotes) {
        if (cell !== "" || row.length > 0) row.push(cell);
        if (row.length > 0) rows.push(row);
        row = []; cell = "";
        if (char === "\r" && nextChar === "\n") i++;
      } else {
        cell += char;
      }
    }
    if (cell !== "" || row.length > 0) row.push(cell);
    if (row.length > 0) rows.push(row);
    return rows;
  }

  // 渲染单元格，支持多链接
  function renderCell(cell) {
    return String(cell).split(/\s+/).map(part => {
      if (/^https?:\/\/[^\s]+$/i.test(part.trim())) {
        return `<a href="${part}" target="_blank" rel="noopener">${part}</a>`;
      }
      return part;
    }).join(" ");
  }

  // 渲染表格
  function renderTable(data) {
    if (!data || data.length === 0) {
      document.getElementById("csv-table").innerHTML = "无数据";
      return;
    }
    let html = "<table>";
    html += "<thead><tr>";
    data[0].forEach((cell, idx) => {
      html += `<th>${cell}<br><input type="text" style="width:90%" data-col="${idx}" oninput="filterTable()" placeholder="搜索"></th>`;
    });
    html += "</tr></thead><tbody id=\"csv-tbody\">";
    const colCount = data[0].length;
    for (let i = 1; i < data.length; i++) {
      html += `<tr${i % 2 === 1 ? ' class="even"' : ""}>`;
      for (let j = 0; j < colCount; j++) {
        const cell = data[i][j] !== undefined ? data[i][j] : "";
        html += `<td>${renderCell(cell)}</td>`;
      }
      html += "</tr>";
    }
    html += "</tbody></table>";
    document.getElementById("csv-table").innerHTML = html;
  }

  // 列搜索
  let originalData = [];
  window.filterTable = function () {
    const filters = Array.from(document.querySelectorAll("thead input")).map(input => input.value.trim().toLowerCase());
    const tbody = document.getElementById("csv-tbody");
    let html = "", colCount = originalData[0].length, matchCount = 0;
    for (let i = 1; i < originalData.length; i++) {
      const row = originalData[i];
      let show = true;
      for (let j = 0; j < filters.length; j++) {
        if (filters[j] && (!row[j] || row[j].toLowerCase().indexOf(filters[j]) === -1)) {
          show = false; break;
        }
      }
      if (show) {
        matchCount++;
        html += `<tr${i % 2 === 1 ? ' class="even"' : ""}>`;
        for (let j = 0; j < colCount; j++) {
          const cell = row[j] !== undefined ? row[j] : "";
          html += `<td>${renderCell(cell)}</td>`;
        }
        html += "</tr>";
      }
    }
    if (matchCount === 0) {
      html = `<tr><td colspan="${colCount}" style="text-align:center;color:#888;">无匹配数据</td></tr>`;
    }
    tbody.innerHTML = html;
  };

  // 获取url参数并加载csv，防缓存+GBK
  function getCsvUrlFromQuery() {
    const params = new URLSearchParams(window.location.search);
    let url = params.get("url");
    if (!url) {
      // 自动获取同名csv
      const htmlName = window.location.pathname.split('/').pop();
      if (htmlName && htmlName.endsWith('.html')) {
        url = htmlName.replace(/\.html$/i, '.csv');
      }
    }
    return url;
  }
  const csvUrl = getCsvUrlFromQuery();
  if (csvUrl) {
    const urlWithNoCache = csvUrl + (csvUrl.includes('?') ? '&' : '?') + '_t=' + Date.now();
    fetch(urlWithNoCache)
      .then(res => {
        if (!res.ok) {
          throw new Error('notfound');
        }
        return res.blob();
      })
      .then(blob => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsText(blob, 'gbk');
      }))
      .then(text => {
        originalData = parseCSV(text);
        renderTable(originalData);
      })
      .catch(err => {
        document.getElementById("csv-table").innerHTML =
          `请在地址栏 url 参数中指定 CSV 文件地址，或将同名 csv 文件与 html 放在一起<br>
          <span style="color:#888;">示例：http://192.168.1.101:8080/chfs/shared/showcsv.html?v=1<mark>&url=1.csv</mark> 或 http://192.168.1.101:8080/chfs/shared/showcsv.html?v=1<mark>&url=http://192.168.1.101:8080/chfs/shared/1.csv</mark></span>`;
      });
  } else {
    document.getElementById("csv-table").innerHTML =
      "请在地址栏 url 参数中指定 CSV 文件地址，或将同名 csv 文件与 html 放在一起";
  }
    </script>
  </body>
</html>
